package com.igelato.controller.AdminUser;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.igelato.model.AdminUser;
import com.igelato.response.AppException;
import com.igelato.response.ErrorCodeMsgEnum;
import com.igelato.response.R;
import com.igelato.service.AdminUserService;
import com.igelato.utils.JwtToken;
import com.igelato.utils.ThreadLocalTool;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;


/**
 * @Description:
 * @Author: wht
 * @Date: 2023-12-30
 */
@Slf4j
@RestController
@RequestMapping("/")
@Api(tags = {"操作管理员"})
public class AdminUserController {
    @Autowired
    AdminUserService adminUserService;


    // 自己 ---------------------------------------------
    @ApiOperation("登录（通过密码）")
    @PostMapping("/loginByPwd")
    public <T> R<T> loginByPwd(@RequestBody LoginByPwdDto loginDto) {
        AdminUser adminUser = adminUserService.loginByPwd(loginDto);

//        设置token
        String token = JwtToken.getToken(adminUser.getId());
        ThreadLocalTool.setToken(token);

        return R.successMsgData("登录成功！", adminUserService.getResAdminUser(adminUser));
    }

    @ApiOperation("获取token")
    @GetMapping("/getUserInfoByToken")
    public <T> R<T> getUserInfoByToken() {
        AdminUser adminUser = ThreadLocalTool.getUser();
        return R.successData(adminUserService.getResAdminUser(adminUser));
    }

    @ApiOperation("修改自己的密码")
    @PatchMapping("/resetMyPwd")
    public <T> R<T> resetMyPwd(@RequestBody ResetMyPwdDto resetMyPwdDto) {
        Boolean res = adminUserService.resetMyPwd(resetMyPwdDto);

        if (res) {
            return R.successMsg("修改成功！");
        } else {
            throw new AppException(ErrorCodeMsgEnum.UPDATE_ERROR);
        }
    }

    @ApiOperation("修改自己的信息")
    @PatchMapping("/updateMyInfo")
    public <T> R<T> updateMyInfo(@RequestBody AdminUserUpdateDto updateDto) {
        AdminUser adminUser = new AdminUser();
        BeanUtils.copyProperties(updateDto, adminUser);
        // 只能修改自己的用户信息，所以id不能是前端传进来的值
        AdminUser user = ThreadLocalTool.getUser();
        adminUser.setId(user.getId());

        boolean res = adminUserService.updateById(adminUser);

        if (res) {
            return R.successMsg("修改成功！");
        } else {
            throw new AppException(ErrorCodeMsgEnum.UPDATE_ERROR);
        }
    }

    @ApiOperation("获取腾讯云对象存储的存储桶token")
    @GetMapping("/getCosTempToken")
    public <T> R<T> getCosTempToken() {
        Map res = adminUserService.getCosTempToken();
        return R.successData(res);
    }


    // 员工 ---------------------------------------------
    @ApiOperation("新增一个员工")
    @PutMapping("/addOneEmployee")
    public <T> R<T> addOneEmployee(@RequestBody AdminUserAddDto addDto) {
        AdminUser adminUser = new AdminUser();
        BeanUtils.copyProperties(addDto, adminUser);
        adminUser.setRole_ids_json(JSON.toJSONString(addDto.getRole_ids()));
        boolean res = adminUserService.save(adminUser);

        if (res) {
            return R.successMsg("添加成功！");
        } else {
            throw new AppException(ErrorCodeMsgEnum.ADD_ERROR);
        }
    }

    @ApiOperation("删除一个员工")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "员工id", dataType = "Integer", required = true)}
    )
    @DeleteMapping("/deleteOneEmployee/{id}")
    public <T> R<T> deleteOneEmployee(@PathVariable("id") Integer id) {
        if (id == null) {
            throw new AppException(ErrorCodeMsgEnum.REQUEST_PARAMS_ERROR);
        }
        boolean res = adminUserService.removeById(id);

        if (res) {
            return R.successMsg("删除成功！");
        } else {
            throw new AppException(ErrorCodeMsgEnum.DELETE_ERROR);
        }
    }

    @ApiOperation("重置一个员工密码")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "员工id", dataType = "Integer", required = true)}
    )
    @PatchMapping("/resetOneEmployeePwd/{admin_user_id}")
    public <T> R<T> resetOneEmployeePwd(@PathVariable("admin_user_id") Integer admin_user_id) {
        if (admin_user_id == null) {
            throw new AppException(ErrorCodeMsgEnum.REQUEST_PARAMS_ERROR);
        }
        Boolean res = adminUserService.resetOnePwd(admin_user_id);

        if (res) {
            return R.successMsg("重置密码成功！");
        } else {
            throw new AppException(ErrorCodeMsgEnum.UPDATE_ERROR);
        }
    }

    @ApiOperation("修改一个员工信息")
    @PatchMapping("/updateOneEmployee")
    public <T> R<T> updateOneEmployee(@RequestBody AdminUserUpdateDto updateDto) {
        AdminUser adminUser = new AdminUser();
        BeanUtils.copyProperties(updateDto, adminUser);
        adminUser.setRole_ids_json(JSON.toJSONString(updateDto.getRole_ids()));
        boolean res = adminUserService.updateById(adminUser);

        if (res) {
            return R.successMsg("修改成功！");
        } else {
            throw new AppException(ErrorCodeMsgEnum.UPDATE_ERROR);
        }
    }


//    @ApiOperation("通过id获取一个员工")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "id", value = "员工id", dataType = "Integer", required = true)}
//    )
//    @GetMapping("/getOneEmployee/{id}")
//    public <T> R<T> getOneEmployee(@PathVariable("id") Integer id) {
//        if (id == null) {
//            throw new AppException(ErrorCodeMsgEnum.REQUEST_PARAMS_ERROR);
//        }
//        AdminUser adminUser = adminUserService.getById(id);
//
//        return R.successData(adminUser);
//    }

    @ApiOperation("分页获取员工列表")
    @PostMapping("/getEmployeeList")
    public <T> R<T> getEmployeeList(@Valid @RequestBody AdminUserSearchDto searchDto) throws IllegalAccessException {
        QueryWrapper<AdminUser> queryWrapper = new QueryWrapper<>();

        Field[] fields = searchDto.getClass().getDeclaredFields();
        for (Field field : fields) {
            String name = field.getName();
            if (name.equals("page_num") || name.equals("page_size")) continue;
            field.setAccessible(true); // 必须将字段设置为可访问
            Object value = field.get(searchDto);
            if (value == null || (value instanceof String && "".equals(value))) continue;
            queryWrapper.eq(name, value);

        }

        Page<AdminUser> page = new Page<>(searchDto.getPage_num(), searchDto.getPage_size());
        adminUserService.page(page, queryWrapper);

        HashMap<Object, Object> res = new HashMap<>();
        res.put("page_size", page.getSize());
        res.put("page_num", page.getCurrent());
        res.put("total", page.getTotal());
        res.put("list", page.getRecords());
        return R.successData(res);
    }

//    @ApiOperation("获取所有员工列表")
//    @GetMapping("/getAllEmployeeList")
//    public <T> R<T> getAllEmployeeList() {
//        List<AdminUser> list = adminUserService.list();
//
//        return R.successData(list);
//    }
}
